<?php
/**
 * Created by PhpStorm.
 * User: anyuzhe
 * Date: 2017/3/26
 * Time: 15:06
 */

namespace App\Repositories;

use App\User;
use App\ZL\Library\Curl;
use App\ZL\Library\ErrorCode;
use App\ZL\Library\Openssl;
use InfyOm\Generator\Common\BaseRepository;
use Illuminate\Support\Collection;
use Illuminate\Container\Container as App;

class UsersRepository extends BaseRepository {

    protected $store;

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function model() {
        return 'App\User';
    }

    public function checkHasAndSaveGetInfoByWechat($access_token,$openid,$shop_id,$save=true)
    {
        $user = $this->checkHas($openid,$shop_id);
        if(!$save){
            return $user;
        }
        if(!$user || !$user['nickname'] || !$user['openid']){
            $userinfo = $this->getUserInfoByWechat($access_token,$openid);
            if($userinfo){
                $userinfo['id'] = isset($user['id'])?$user['id']:null;
                $user = $this->checkHasAndSaveInfoByWechat($userinfo,$shop_id);
            }
        }
        return $user;
    }


    public function getUserInfoByWechat($accessToken,$openId)
    {
//        $app = new Application(c('easywechat_config'));
//        // 获取用户实例
//        $userService = $app->user;
//        return $userService->get($openId);
        //通过网页授权access_token和openid获取用户基本信息（支持UnionID机制）
        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$accessToken.'&openid='.$openId.'&lang=zh_CN';
        //转成对象
        $user_info = json_decode(Curl::get($user_info_url),true);
        $this->qc = $user_info;
        $weixin_openid = $user_info['openid'];
        if(!isset($weixin_openid)){
            echo '信息获取失败，请返回刷新后重新操作';die;
        }
        return $user_info;
    }

    public function checkHasAndSaveInfoByWechat($user, $shop_id)
    {
        saveNotification($user,'userinfowechat');
        $hasuser = $this->checkHas($user['openid'], $shop_id);

        $data = [
            'shop_id'=>$shop_id,
            'openid'=>$user['openid'],
            'nickname'=>$user['nickname'],
            'avatar_url'=>$user['headimgurl'],
            'sex'=>$user['sex'],
            'city'=>$user['city'],
            'session_id'=>getSessionId(),
        ];
        if(isset($user['unionid'])){
            $data['unionid'] = $user['unionid'];
        }
        if(!$hasuser){
            $new = $this->create($data);
////            $bonus = Bonus::where('name','新用户满减券')->where('user_id',0)->first();
////            $bonus->user_id = $new->id;
////            $bonus->save();
            return $new;
        }else{
            $this->update($data,$hasuser['id']);
            return $hasuser;
        }
    }

    public function getOneByOpenid($openId,$is_xcx=true)
    {
        if($is_xcx)
            $field = 'xcx_openid';
        else
            $field = 'openid';
            return User::where($field,$openId)->first();
    }


    public function saveToken($id,$sessionKey)
    {
        $this->update(['remember_token'=>$sessionKey],$id);
    }

    public function saveTokenAndGetSecret($id,$sessionKey)
    {
        $this->saveToken($id,$sessionKey);
        $data = ['id'=>$id,'remember_token'=>$sessionKey];
        $key = config('app.aes_key');
        $iv = config('app.aes_iv');
        $encrypted = Openssl::encryptByAes($key,$iv,json_encode($data));
        return base64_encode($encrypted);
    }

    public function checkHas($openid,$shop_id)
    {
        return User::where('openid', $openid)->where('shop_id', $shop_id)->first();
    }
}